<?php
/**
 * MyPDO
 * @author LiYuZhao<562405704@qq.com>
 * @blog http://www.liyuzhao.cn/
 */
class MyPDO
{
    protected static $_instance = null;
    protected $dbName = '';
    protected $dsn;
    protected $dbh;

    /**
     * 构造
     * @return MyPDO
     */
    private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        $conf = include('mysql.conf.php');
        try {
            $this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;
            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
            $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
            $this->dbh->exec('SET '.$conf['dbName'].' '.$conf['dbCharset']);
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }

    /**
     * 防止克隆
     *
     */
    private function __clone() {}

    /**
     * Singleton instance
     *
     * @return Object（mysql资源id）
     */
    public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
    {
        //读取数据库配置文件
        $conf = include('mysql.conf.php');
        if(empty($dbHost)){
            $dbHost = $conf['dbHost'];
        }
        if(empty($dbUser)){
            $dbUser = $conf['dbUser'];
        }
        if(empty($dbPasswd)){
            $dbPasswd = $conf['dbPasswd'];
        }
        if(empty($dbName)){
            $dbName = $conf['dbName'];
        }
        if(empty($dbCharset)){
            $dbCharset = $conf['dbCharset'];
        }
        if (self::$_instance === null) {
            self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
        }
        return self::$_instance;
    }

    /**
    执行有返回值的查询，返回一维数组  可以通过链式操作，可以通过这个类封装的操作获取数据
     */
    public function fetch($sql){
        if(empty($sql)){
            return false;
        }
        $res = $this->dbh->query($sql);
        $arr = [];
        if(!empty($res)){
            foreach($res as $row){
                $arr = $row;
                unset($arr[0]);
                break;
            }
            return $arr;
        }else{
            return false;
        }
    }

    /**
    执行有返回值的查询，返回二维数组  可以通过链式操作，可以通过这个类封装的操作获取数据
     */
    public function fetchall($sql){
        if(empty($sql)){
            return false;
        }
        $res = $this->dbh->query($sql);
        foreach($res as $row){
            $arr[] = $row;
        }
        return $arr;
    }

    /**
     * execSql 执行SQL语句
     *
     * @param String $strSql
     * @param Boolean $debug
     * @return Int
     */
    public function execSql($strSql)
    {
        $result = $this->dbh->exec($strSql);
        return $result;
    }

}
?>